package service

import (
	"context"
	libNet "net"
	"smart-flow/monitor/config"
	"smart-flow/monitor/logger"
	"smart-flow/monitor/proto"
	"time"

	"github.com/shirou/gopsutil/v4/net"
	"go.uber.org/zap"
)

func RunningContainer(port uint32) bool {
	connections, err := net.ConnectionsWithContext(context.Background(), "tcp")
	if err != nil {
		logger.Logger.Error("[管控] 获取网络连接失败", zap.Error(err))
		return false
	}
	count := 0
	for _, conn := range connections {
		if conn.Status == "LISTEN" && conn.Laddr.Port == port {
			ipString := conn.Laddr.IP
			ip := libNet.ParseIP(ipString)
			if ip == nil {
				continue
			}
			if ip.IsUnspecified() || ip.IsLoopback() {
				continue
			}
			if ip.To4() == nil {
				ContainersInstance().AddV6Container(ipString, &proto.ContainerInfo{
					MaxDown: config.AppConfig().Dy.MaxDownV6 * config.MBit,
					ContainerReq: proto.ContainerReq{
						Timestamp:     time.Now().Unix(),
						InterfaceName: config.AppConfig().Monitor.InterfaceName,
						ContainerIp:   ipString,
						V6Addr:        true,
						TcpDown:       0,
						UdpDown:       0,
						HttpDown:      0,
						Down:          0,
					},
				})
			} else {
				ContainersInstance().AddV4Container(ipString, &proto.ContainerInfo{
					MaxDown: config.AppConfig().Dy.MaxDownV4 * config.MBit,
					ContainerReq: proto.ContainerReq{
						Timestamp:     time.Now().Unix(),
						InterfaceName: config.AppConfig().Monitor.InterfaceName,
						ContainerIp:   ipString,
						V6Addr:        false,
						TcpDown:       0,
						UdpDown:       0,
						HttpDown:      0,
						Down:          0,
					},
				})
			}
			count++
			logger.Logger.Info("[管控] 正在运行的Container", zap.String("ip", ipString))
		}
	}
	if count == 0 {
		logger.Logger.Error("[管控] 未发现运行中的Container")
		return false
	}
	logger.Logger.Info("[管控] 运行中的Container数量", zap.Int("count", count))
	return true
}
